package com.zhss.redis.hash;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;

import java.util.stream.IntStream;

/**
 * @ClassName ShortUrlDemo
 * @Description TODO
 * @Author leejiliang
 * @DateTime 2021/9/9 22:07
 * @Version 1.0
 */
public class ShortUrlDemo {

	private static final String[] X36_ARRAY = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z".split(",");

	HostAndPort hostAndPort = new HostAndPort("121.4.79.149", 6379);
	Jedis jedis = new Jedis(hostAndPort);

	public static void main(String[] args) {
		ShortUrlDemo shortUrlDemo = new ShortUrlDemo();
//		shortUrlDemo.setSeed(234333443L);
		String shortUrl = shortUrlDemo.getShortUrl("https://www.baidu.com/aaa/dddd/bbb/dddd/1/2334fdsfsdgdfd");
		System.out.println(shortUrl);
		shortUrlDemo.clickShortUrl(shortUrl);
		System.out.println(shortUrlDemo.getShortUrlAccessCount(shortUrl));
		System.out.println(shortUrlDemo.getLongUrl(shortUrl));
	}

	public void setSeed(Long value) {
		jedis.set("short_url_seed", value + "");
	}

	public String getShortUrl(String url) {
		Long shortUrlSeed = jedis.incr("short_url_seed");
		StringBuffer sBuffer = new StringBuffer();

		if(shortUrlSeed == 0) {
			sBuffer.append("0");
		}
		while(shortUrlSeed > 0) {
			sBuffer.append(X36_ARRAY[(int)(shortUrlSeed % 36)]);
			shortUrlSeed = shortUrlSeed / 36;
		}

		String shortUrl = sBuffer.reverse().toString();

		jedis.hset("short_url_access_count", shortUrl, "0");
		jedis.hset("short_url_mapping", shortUrl, url);
		return shortUrl;
	}

	public void clickShortUrl(String shortUrl) {
		IntStream.rangeClosed(1, 10).forEach(i->{
			jedis.hincrBy("short_url_access_count", shortUrl, 1);
		});
	}

	public long getShortUrlAccessCount(String shortUrl) {
		return Long.valueOf(jedis.hget("short_url_access_count", shortUrl));
	}

	public String getLongUrl(String shortUrl) {
		return jedis.hget("short_url_mapping", shortUrl);
	}
}
